<template>
    <!-- 标题 -->
    <h2 :style="{ color: titleInfo? titleInfo.color:'' }">{{ titleInfo? titleInfo.value:'' }}</h2>
    <div @click="$store.commit('add')">count:{{ count }}</div>
    <div>doubleCount:{{ doubleCount }}</div>
    <!-- 新增代办事项 -->
    <input type="text" v-model="todoName" @keydown.enter="addTodo(newTodo(todoName))" />
    <!-- 代办事项列表 -->
    <div v-for="item in items" :key="item.id">{{ item.name }}</div>
</template>
<script lang="ts" setup>
import { ref, computed, defineProps } from "vue";
import type { PropType } from 'vue'
import type { Todo, TitleInfo } from '../../types'

// setup中使用useStore时需要类型化，共需要3步
// 1.定义'InjectionKey'
// 2.app安装时提供'InjectionKey'
// 3.传递‘InjectionKey’给useStore
import { useStore } from "vuex";
import { key } from "../store";

let store = useStore(key);
let count = computed(() => store.state.count)
let doubleCount = computed(() => count.value * 2)


//熟悉声明
defineProps({
    titleInfo: {
        type: Object as PropType<TitleInfo>,
        require: true
    }
})

let items = computed(() => store.state.todos?.items);
let todoName = ref('');

//todos初始化
store.dispatch('todos/initTodo')

const newTodo = (todoName: string): Todo => {
    return {
        id: items.value!.length + 1,
        name: todoName,
        completed: false
    }
};

const addTodo = (todo: Todo): void => {
    store.commit('/todos/initTodo',todo);
    todoName.value = '';
}

</script>
<style></style>